package com.JUC;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class JUC02_communication {
    public static void main(String[] args) {
        NUM num = new NUM();

        new Thread(()->{
            for (int i = 0; i < 10; i++){
                try {
                    // 加法
                    num.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"Thread_A").start();
        new Thread(()->{
            for (int i = 0; i < 10; i++){
                try {
                    // 减法
                    num.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"Thread_B").start();
        new Thread(()->{
            for (int i = 0; i < 10; i++){
                try {
                    // 加法
                    num.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"Thread_C").start();
        new Thread(()->{
            for (int i = 0; i < 10; i++){
                try {
                    // 减法
                    num.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"Thread_D").start();
    }
}
class NUM{
    private int number = 0;

    private Lock lock = new ReentrantLock();
    //使用 lock 对应的 condition 对象
    private Condition condition = lock.newCondition();


    public void increment() throws InterruptedException {

        // lock 模块
        // 上锁
        lock.lock();
        try {
            //2.1 判断
            while (number != 0){
                condition.await();
            }
            //2.2 干活
            number++;
            System.out.println(Thread.currentThread().getName() + "\t"+number);
            //2.3 通知(唤醒)
            condition.signalAll();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            // 开锁
            lock.unlock();
        }

    }

    public void decrement() throws InterruptedException {
        lock.lock();
        try {
            //2.1 判断
            while (number == 0){
                condition.await();
            }
            //2.2 干活
            number--;
            System.out.println(Thread.currentThread().getName() + "\t"+number);
            //2.3 通知(唤醒)
            condition.signalAll();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            // 开锁
            lock.unlock();
        }
    }
}
